'use server'

import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
import { Decimal } from "@prisma/client/runtime/library"

interface CreateProductData {
  name: string
  code: string
  description?: string
  price: string
  unit: string
  stock: string
  categoryId: string
}

export async function createProduct(data: CreateProductData) {
  try {
    const product = await prisma.product.create({
      data: {
        name: data.name,
        code: data.code,
        description: data.description || null,
        price: new Decimal(data.price),
        unit: data.unit,
        stock: parseInt(data.stock),
        categoryId: parseInt(data.categoryId)
      },
      include: {
        category: true
      }
    })

    revalidatePath('/dashboard/inventory/products')
    return { success: true, data: product }
  } catch (error) {
    console.error('创建商品失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '创建商品失败'
    }
  }
}

interface UpdateProductData {
  name: string
  code: string
  description?: string
  price: string
  unit: string
  stock: string
  categoryId: string
}

export async function updateProduct(id: number, data: UpdateProductData) {
  try {
    const product = await prisma.product.update({
      where: { id },
      data: {
        name: data.name,
        code: data.code,
        description: data.description || null,
        price: new Decimal(data.price),
        unit: data.unit,
        stock: parseInt(data.stock),
        categoryId: parseInt(data.categoryId)
      },
      include: {
        category: true
      }
    })

    revalidatePath('/dashboard/inventory/products')
    return { success: true, data: product }
  } catch (error) {
    console.error('更新商品失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '更新商品失败'
    }
  }
}

export async function deleteProduct(id: number) {
  try {
    const product = await prisma.product.delete({
      where: { id }
    })

    revalidatePath('/dashboard/inventory/products')
    return { success: true, data: product }
  } catch (error) {
    console.error('删除商品失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '删除商品失败'
    }
  }
} 